package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class CalculateDepthSolution {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(5);
        treeNode.left = null;
        treeNode.right = new TreeNode(2);
        calculateDepth2(treeNode);
    }

    public static int calculateDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(calculateDepth(root.left), calculateDepth(root.right)) + 1;
    }

    public static int calculateDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.offer(root);
        while (!treeNodeQueue.isEmpty()) {
            int size = treeNodeQueue.size();
            for (int i = 0; i<size; i++) {
                TreeNode temp = treeNodeQueue.poll();
                if (temp.left != null) {
                    treeNodeQueue.offer(temp.left);
                }
                if (temp.right != null) {
                    treeNodeQueue.offer(temp.right);
                }
            }
            depth++;
        }
        return depth;
    }
}
